package com.zee.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zee.admin.shiro.AdminSecurityUser;
import com.zee.admin.shiro.AdminUserDetail;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

// 起始版本 3.3.3(推荐)
@Component
public class TableFieldFillConfig implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        //System.out.println("===========新增时自动填充字段");
        AdminUserDetail user = AdminSecurityUser.getUser();
        //获取得到admin模块的AdminUserDetail则自动填充，获取不到可能没登录或者是home模块的
        if (user.getId() != null) {
            //创建者
            this.strictInsertFill(metaObject, "creator", Integer.class, user.getId());
            //更新者
            this.strictInsertFill(metaObject, "updater", Integer.class, user.getId());
            //创建者部门
            this.strictInsertFill(metaObject, "deptId", Integer.class, user.getDeptId());
        }

        this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        AdminUserDetail user = AdminSecurityUser.getUser();
        //获取得到admin模块的AdminUserDetail则自动填充，获取不到可能没登录或者是home模块的
        if (user.getId() != null) {
            this.strictInsertFill(metaObject, "updater", Integer.class, user.getId());
        }
        //System.out.println("===========更新时自动填充字段");
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
    }
}
